#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2020/3/4  8:50
# @Author: 余浪人
# @email: yulangren520@gmail.com

import os, requests
from pathlib import Path
from apps import get_sys_url
from apps.control import sys_bp
from flask_login import login_required
from flask import request, render_template, jsonify
from apps.models.plugs_model import TL_Plugs_Model


@sys_bp.route('/plug_list', endpoint='plug_list', methods=['GET', 'DELETE', 'PUSH', 'INSTALL'])
@login_required
def plug_list():
    data_id = request.form.get('data')
    temporary_path = os.path.join(get_sys_url(), 'apps/temporary')
    temp_dir = Path(temporary_path)
    if request.method == 'DELETE':
        return jsonify({"status": 0, 'msg': '卸载成功'})
    elif request.method == 'PUSH':
        error = None
        if not temp_dir.exists():
            try:
                os.makedirs(temporary_path)
            except:
                error = '目录创建失败！'
        elif not os.access(temporary_path, os.W_OK):
            error = '未检测到写入权限！'
        if error: return jsonify({"status": 1, 'msg': error})
        # try:
        #     content_b = requests.get('').content # todo 下载远程资源
        #     with open(f'{temporary_path}/{data_id}','wb')as fp:fp.write(content_b)
        # except:return jsonify({'status':1,'msg':'下载数据失败'})
        return jsonify({"status": 0, 'msg': '下载成功'})
    elif request.method == 'INSTALL':
        return jsonify({"status": 0, 'msg': '安装成功'})
    data_list = []
    # 请求官方接口返回json数据及下载插件资源 todo 对接
    '模拟json数据'
    already_install = {k.plug_logo: k for k in TL_Plugs_Model.query.filter(TL_Plugs_Model.install_status == 1).all()}  # 已安装插件
    json_data = {
        # 'sdfsfasdfasdf1':{
        #     'plug_logo':'sdfsfasdfasdf',
        #     'plug_name':'快速采集插件',
        #     'plug_version':'v1.0',
        #     'plug_class':'插件类型',
        #     'install_status':0,
        #     'install_time':'2020.9.10 12:12:12'
        # },
    }  # json返回模拟数据
    for k, v in json_data.items():
        if k in already_install:
            v['install_status'] = already_install[k]['install_status']
            v['install_time'] = already_install[k]['install_time']
        data_list.append(v)
    return render_template('system_template/plugs_list.html', data_list=data_list)
